# encoding:utf8
import tensorflow as tf
import logging
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np

logging.basicConfig(level=logging.DEBUG)
LOGGING = logging.getLogger("tfrecord_writer")


def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))


def _byte_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))


def main():
    mnist = input_data.read_data_sets("E:/mnist", dtype=tf.uint8, one_hot=True)
    LOGGING.debug("read_data_sets finish")

    images = mnist.train.images
    labels = mnist.train.labels
    pixels = images.shape[1]
    LOGGING.info("images shape: %s, label shape: %s", images.shape, labels.shape)
    num_examples = mnist.train.num_examples

    filename = "E:/mnist.tfrecords"
    writer = tf.python_io.TFRecordWriter(filename)

    for index in range(num_examples):
        image_raw = images[index].tostring()
        example = tf.train.Example(features=tf.train.Features(feature={
            'pixels': _int64_feature(pixels),
            'label': _int64_feature(np.argmax(labels[index])),
            'image_raw': _byte_feature(image_raw)
        }))
        writer.write(example.SerializeToString())

    LOGGING.info("tfrecord write finish")


if __name__ == "__main__":
    main()
